package com.weixin.program.task;

import lombok.Data;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;


/**
 * 延迟任务
 */
@Data
public class Task implements Delayed {

    String taskName;
    String toUserId;
    long time;

    public Task(String taskName, String toUserId, long givenTime, long delayTime, TimeUnit unit) {
        this.taskName = taskName;
        this.toUserId = toUserId;
        this.time = givenTime + unit.toMillis(delayTime);
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(this.time - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    @Override
    public int compareTo(Delayed o) {
        return (int) (this.getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS));
    }

    /**
     * 获取延迟之后的时间戳
     *
     * @param givenTime
     * @param delayTime
     * @param unit
     * @return
     */
    public static long getDelayTime(long givenTime, long delayTime, TimeUnit unit) {
        return givenTime + unit.toMillis(delayTime);
    }
}
